<?php

namespace App\Http\Controllers\Wechat;

use App\Models\Agency;
use App\Models\Assessment;
use App\Models\Category;
use App\Models\Child;
use App\Models\Game;
use App\Models\Grade;
use App\Models\Tool;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;

class AssessmentController extends BaseController
{
    /**
     *
     * @Date 2020/10/9 上午10:29
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function result(Request $request){
        $user = $this->getUser();

        $query = $request->only(['child_name', 'stage', 'tool_id']);
        $query['user_id'] = $user->id;

        //平台
        $where = Assessment::selectQuery($query);
        $list = Assessment::where($where)->orderBy('id', 'desc')->paginate(config('site.other.paginate'));
        $stage = Assessment::getStage();

        $list = $list->appends($query);

        $tools = Tool::all();
        return frontendView('assessment.result', compact('list', 'stage',  'query', 'user', 'tools'));
    }

    /**
     *
     * @Date 2020/10/9 上午10:29
     * @param $child_id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function index($child_id)
    {
        $child = Child::find($child_id);
        if (empty($child)) {
            return back()->with('error', __('The page you requested was not found'))->withInput();
        }

        $user = $this->getUser();
        if (!$user->can('allow', $child)) {
            return back()->with('error', __('Sorry, you are not authorized to access this page.'))->withInput();
        }

        $list = Assessment::where('child_id', $child_id)->paginate(config('site.other.paginate'));

        $stage = Assessment::getStage();

        return frontendView('assessment.index', compact('list', 'child', 'stage'));
    }

    public function add($child_id, Request $request)
    {

        $child = Child::find($child_id);
        if (empty($child)) {
            return back()->with('error', __('The page you requested was not found'))->withInput();
        }
        $user = $this->getUser();
        if (!$user->can('allow', $child)) {
            return back()->with('error', __('Sorry, you are not authorized to access this page.'))->withInput();
        }
        if ($request->isMethod('post')) {
            $this->validate($request, [
                'age' => 'required|min:0.1|max:50',
                'agedevelop' => 'required|min:0.1|max:50',
                'tool_id' => 'required|integer|exists:tools,id',
                'assess_time' => 'required|date',
                'stage' => 'required|in:0,1,2',
            ], [], [
                'age' => '生理年龄',
                'agedevelop' => '发展年龄',
                'tool' => '评估工具/量表',
                'assess_time' => '测评时间',
                'stage' => '测评阶段',
            ]);

            $data = $request->only(['age', 'agedevelop', 'tool_id', 'assess_time', 'stage']);
            $data['child_id'] = $child_id;
            $data['user_id'] = $child->user_id;
            $data['agency_id'] = $child->user->agency_id;

            //if ($child->assessments()->create($data)) {
            if (Assessment::create($data)) {
                return redirect()->route('wechat.assessment.index', ['child_id' => $child_id])->with('success', __('Create success'));
            }

            return back()->with('error', __('Create failed'))->withInput();
        } else {
            $stage = Assessment::getStage();
            $tools = Tool::where('status', 1)->get();
            return frontendview('assessment.add', compact('child', 'stage', 'tools'));
        }
    }

    public function edit($id, Request $request)
    {
        $assessment = Assessment::find($id);
        if (empty($assessment)) {
            return back()->with('error', __('The page you requested was not found'))->withInput();
        }
        $user = $this->getUser();
        if (!$user->can('allow', $assessment->child)) {
            return back()->with('error', __('Sorry, you are not authorized to access this page.'))->withInput();
        }
        if ($request->isMethod("post")) {
            $this->validate($request, [
                'age' => 'required|numeric|min:0.1|max:50',
                'agedevelop' => 'required|numeric|min:0.1|max:50',
                'tool_id' => 'required|integer|exists:tools,id',
                'assess_time' => 'required|date',
                'stage' => 'required|in:0,1,2',
            ], [], [
                'age' => '生理年龄',
                'agedevelop' => '评估后发展年龄',
                'tool_id' => '评估工具/量表',
                'assess_time' => '测评时间',
                'stage' => '测评阶段',
            ]);
            $data = $request->only(['age', 'agedevelop', 'tool_id', 'assess_time', 'stage']);

            if ($assessment->update($data)) {
                return redirect()->route('wechat.assessment.index', ['child_id' => $assessment->child_id])->with('success', __('Edit success'));
            }

            return back()->with('error', __('Edit failed'));
        } else {
            $stage = Assessment::getStage();
            $tools = Tool::where('status', 1)->get();
            return frontendview('assessment.edit', compact('assessment', 'stage', 'tools'));
        }
    }

    public function delete($id)
    {
        $assessment = Assessment::find($id);
        if (empty($assessment)) {
            return back()->with('error', __('The page you requested was not found'))->withInput();
        }
        $user = $this->getUser();
        if (!$user->can('allow', $assessment->child)) {
            return back()->with('error', __('Sorry, you are not authorized to access this page.'))->withInput();
        }
        if ($assessment->delete()) {
            return back()->with('success', __('Delete success'));
        }

        return back()->with('error', __('Delete failed'));
    }

    public function view($id)
    {
        $assessment = Assessment::find($id);
        if (empty($assessment)) {
            return back()->with('error', __('The page you requested was not found'))->withInput();
        }
        $user = $this->getUser();
        if (!$user->can('allow', $assessment->child)) {
            return back()->with('error', __('Sorry, you are not authorized to access this page.'))->withInput();
        }
        $stage = Assessment::getStage();
        return frontendview('assessment.view', compact('assessment', 'stage'));
    }
    public function ajaxdata($child_id){
        $child = Child::find($child_id);
        if (empty($child)){
            return response()->json(['status'=>404, 'data'=>[]]);
        }
        $list = Assessment::with("tool")->where('child_id', $child_id)->get();
        if (count($list) == 0){
            return response()->json(['status'=>400, 'data'=>[]]);
        }

        $result = [];
        foreach ($result as $item){
            if (!isset($result[$item['tool_id']])){
                $result[$item['tool_id']]['name'] = $item->tool->name;
            }

            $result[$item['tool_id']]['data'][] = ['x'=>$item->assess_time, 'y'=>$item->agedevelop];
        }
        $list->each(function($item) use (&$result){
            if (!isset($result[$item['tool_id']])){
                $result[$item['tool_id']]['name'] = $item->tool->name;
                $result[$item['tool_id']]['age']['label'] = '生理年龄';
                $result[$item['tool_id']]['agedevelop']['label'] = '发展年龄';
            }

            $result[$item['tool_id']]['age']['data'][] = ['x'=>date('m/d/Y H:i',strtotime($item->assess_time)), 'y'=>floatval($item->age)];
            $result[$item['tool_id']]['agedevelop']['data'][] = ['x'=>date('m/d/Y H:i',strtotime($item->assess_time)), 'y'=>floatval($item->agedevelop)];
        });

        return response()->json(['status'=>200, 'data'=>$result]);
    }

}
